
#if defined (WIN32) & defined (_DEBUG)
	#define _CRTDBG_MAP_ALLOC
	#include <stdlib.h>
	#include <crtdbg.h>
#endif

#include <iostream>
#include <fstream>
#include <sstream>

#include "Scanner.h"
#include "Parser.h"

#include "Object.h"
#include "Type.h"

#include "Scope.h"
#include "SymbolTable.h"
#include "Code.h"


int Compile(const char* filename)
{
	std::wifstream file(filename);

	if(file.fail())
	{
		std::cout << "Failed to open file " << filename << std::endl;
		return 0;
	}

	mjc::Parser parser(file.rdbuf());
	parser.Parse();

	int errors = parser.GetErrorCount();

	if(errors == 0)//if no errors print generated code and also write it to file
	{
		mjc::Code* code = parser.GetCode();
		std::wcout << L"Generated code" << std::endl << std::endl;
		code->PrintDecoded();

		std::string s(filename);
		size_t p = s.find_first_of('.');

		if(p != std::string::npos)
			s.erase(p);

		std::stringstream ss;
		ss << s << ".out";
		std::ofstream out(ss.str().c_str() , std::ios::out | std::ios::binary);
		code->Write(out);
	}
		
	std::wcout << std::endl << errors << L" errors detected" << std::endl;

	return 1;
}

int main(int argc, char** argv)
{
#if defined (WIN32) & defined (_DEBUG)
	_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
	if(argc < 1)
	{
		std::cout << L"Usage: scanner <input_file_name>" << std::endl;
		return 1;
	}
	
	//initialize token data stuff
	mjc::TokenData::Initialize();

	if(!Compile(argv[1]))
		return 1;

	return 0;
}